package com.dm.library.widgets.wheelview.common;

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;

import com.dm.library.R;
import com.dm.library.utils.DMLog;
import com.dm.library.utils.TimeUtils;
import com.dm.library.widgets.wheelview.OnWheelChangedListener;
import com.dm.library.widgets.wheelview.WheelView;
import com.dm.library.widgets.wheelview.adapters.ArrayWheelAdapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 版    权:  深圳市迪蒙网络科技有限公司
 * 描    述:  通用WheelView，可适配4个WheelView控件的使用
 * <p>
 * setCommonDatas() 用于只有一个WheelView的情况
 * setArea()  适用显示两个或者三个WheelView的地区选择
 * initTime...()   适用显示三个或者四个WheelView的时间选择
 * Created by tangjian on 2016/9/5.
 */
public class CommonUseWheelView extends FrameLayout implements View.OnClickListener, OnWheelChangedListener {
    private static final int TYPE_COMMON = 1;
    private static final int TYPE_AREA = 2;
    private static final int TYPE_TIME = 3;

    private Context mContext;
    private WheelView first_wheel_view;
    private WheelView second_wheel_view;
    private WheelView third_wheel_view;
    private WheelView fourth_wheel_view;

    private List<String> firstContents = new ArrayList<>(5);
    private List<String> secondContents = new ArrayList<>(5);
    private List<String> thirdContents = new ArrayList<>(5);
    private List<String> fourthContents = new ArrayList<>(5);

    private OnSelectedItemChanged mOnSelectedItemChanged;

    private OnClickListener mOnClickListener;

    private int wheelViewType = -1;

    public CommonUseWheelView(Context context) {
        super(context);
        initView(context);
    }

    public CommonUseWheelView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }

    public CommonUseWheelView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context);
    }

    private void initView(Context context) {
        mContext = context;
        View view = LayoutInflater.from(context).inflate(R.layout.common_use_wheel_view, this,false);
        view.findViewById(R.id.select_area_cancel).setOnClickListener(this);
        view.findViewById(R.id.select_area_done).setOnClickListener(this);

        first_wheel_view = (WheelView) view.findViewById(R.id.first_wheel_view);
        second_wheel_view = (WheelView) view.findViewById(R.id.second_wheel_view);
        third_wheel_view = (WheelView) view.findViewById(R.id.third_wheel_view);
        fourth_wheel_view = (WheelView) view.findViewById(R.id.fourth_wheel_view);
        addView(view);

        first_wheel_view.addChangingListener(this);
        second_wheel_view.addChangingListener(this);
        third_wheel_view.addChangingListener(this);
        fourth_wheel_view.addChangingListener(this);

        first_wheel_view.setVisibleItems(5);
        second_wheel_view.setVisibleItems(5);
        third_wheel_view.setVisibleItems(5);
        fourth_wheel_view.setVisibleItems(5);
    }

    public void setOnSelectedItemChanged(OnSelectedItemChanged onSelectedItemChanged) {
        mOnSelectedItemChanged = onSelectedItemChanged;
    }

    public void setOnClickListener(OnClickListener onClickListener) {
        mOnClickListener = onClickListener;
    }

    @Override
    public void onClick(View v) {
        if(v.getId() == R.id.select_area_cancel){
            if (null != mOnClickListener) {
                mOnClickListener.onCancelClick();
            }
        }else if(v.getId() == R.id.select_area_done){
            if (null != mOnClickListener) {
                String second = secondContents.size() > second_wheel_view.getCurrentItem()
                        ? secondContents.get(second_wheel_view.getCurrentItem()) : "";

                String third = thirdContents.size() > third_wheel_view.getCurrentItem()
                        ? thirdContents.get(third_wheel_view.getCurrentItem()) : "";

                String fourth = fourthContents.size() > fourth_wheel_view.getCurrentItem()
                        ? fourthContents.get(fourth_wheel_view.getCurrentItem()) : "";

                mOnClickListener.onDownClick(firstContents.get(first_wheel_view.getCurrentItem()), second, third, fourth);
            }
            afterItemChanged(true);
        }
    }

    /****
     * 控制View的显示或隐藏
     *
     * @param isShowView
     */
    public void showOrHintView(boolean isShowView) {
        if (isShowView) {
            setVisibility(VISIBLE);
            Animation animation = AnimationUtils.loadAnimation(mContext, R.anim.push_bottom_in);
            startAnimation(animation);
        } else {
            setVisibility(GONE);
            Animation animation = AnimationUtils.loadAnimation(mContext, R.anim.push_bottom_out);
            startAnimation(animation);
        }
    }

    /****
     * 设置wheelView的内容  用于只显示一个WheelView的时候
     *
     * @param firstContents
     */
    public void setCommonDatas(List<String> firstContents) {
        wheelViewType = TYPE_COMMON;
        if (null != firstContents) {
            this.firstContents = firstContents;
            ArrayWheelAdapter yearAdapter = new ArrayWheelAdapter<String>(mContext, firstContents);
            // 设置可见条目数量
            first_wheel_view.setViewAdapter(yearAdapter);
        }
    }

    /***
     * 如果是显示地区选择，则可以使用该方法
     *
     * @param provinceInfos
     * @param isShowThird   是否显示区域信息（县，县级市）
     */
    public void setAreaDatas(final List<ProvinceInfo> provinceInfos, final boolean isShowThird) {
        new Runnable() {
            @Override
            public void run() {
                mCitiesDatas = new HashMap<String, List<String>>(10);
                if (null != provinceInfos && provinceInfos.size() != 0) {
                    for (ProvinceInfo provinceInfo : provinceInfos) {
                        firstContents.add(provinceInfo.getName());
                        List<String> cityTemps = new ArrayList<String>(10);
                        for (ProvinceInfo.CityInfo cityInfo : provinceInfo.getList()) {
                            cityTemps.add(cityInfo.getName());

                            if (isShowThird) {
                                List<String> areaTemp = new ArrayList<String>(10);
                                for (ProvinceInfo.CityInfo.AreaInfo areaInfo : cityInfo.getList()) {
                                    areaTemp.add(areaInfo.getName());
                                }
                                mAreasDatas.put(cityInfo.getName(), areaTemp);
                            }
                        }
                        mCitiesDatas.put(provinceInfo.getName(), cityTemps);
                    }
                }
                post(new Runnable() {
                    @Override
                    public void run() {
                        if(firstContents.size() > 0){
                            ArrayWheelAdapter firstAdapter = new ArrayWheelAdapter<String>(mContext, firstContents);
                            first_wheel_view.setViewAdapter(firstAdapter);
                            first_wheel_view.setCurrentItem(0);
                            updateCities();
                        }
                    }
                });
            }
        }.run();
    }

    protected Map<String, List<String>> mCitiesDatas;
    protected Map<String, List<String>> mAreasDatas = new HashMap<>();

    /**
     * 根据当前的省，更新市WheelView的信息
     */
    protected void updateCities() {
        String firstItemContent = firstContents.get(first_wheel_view.getCurrentItem());
        secondContents = mCitiesDatas.get(firstItemContent);
        if (null == secondContents) {
            secondContents = new ArrayList<String>();
        }
        second_wheel_view.setViewAdapter(new ArrayWheelAdapter<String>(mContext, secondContents));
        second_wheel_view.setCurrentItem(0);

        if (third_wheel_view.getVisibility() == VISIBLE) {
            updateAreas();
        } else {
            afterItemChanged(false);
        }
    }

    /***
     * 更新地区： 县，县级市
     */
    private void updateAreas() {
        String secondItemContent = secondContents.get(second_wheel_view.getCurrentItem());
        thirdContents = mAreasDatas.get(secondItemContent);
        if (null == thirdContents) {
            thirdContents = new ArrayList<String>();
        }
        third_wheel_view.setViewAdapter(new ArrayWheelAdapter<String>(mContext, thirdContents));
        third_wheel_view.setCurrentItem(0);
        afterItemChanged(false);
    }

    /****
     * 如果是时间选择，则调用该方法
     */
    public void initTimeDatas(boolean isShowHour) {
        canGetDayVisibleItem = false;
        wheelViewType = TYPE_TIME;
        String currentDate = TimeUtils.getTime(System.currentTimeMillis(), TimeUtils.DATE_FORMAT_DATE); //2015-09-19
        String[] dates = currentDate.split("-");
        String year = dates[0];
        String month = dates[1].startsWith("0") ? dates[1].substring(1) : dates[1];
        String day = dates[2];
        firstContents = DateUtil.getInstance().getYearList();
        secondContents = DateUtil.getInstance().getMounthList();
        thirdContents = DateUtil.getInstance().getDayList(dates[0] + "年", dates[1] + "月");
        fourthContents = DateUtil.getInstance().getHourList("0:00", "23:00");
        setTimeAdapter(year, month, day, isShowHour);
    }

    @SuppressWarnings("rawtypes")
    protected void setTimeAdapter(String year, String month, String day, boolean isShowHour) {
        ArrayWheelAdapter yearAdapter = new ArrayWheelAdapter<String>(mContext, firstContents);
        // 设置可见条目数量
        first_wheel_view.setViewAdapter(yearAdapter);
        int yearInt = Integer.parseInt(year);
        first_wheel_view.setCurrentItem(yearInt - 2015); //初始显示2015年

        ArrayWheelAdapter monthAdapter = new ArrayWheelAdapter<String>(mContext, secondContents);
        second_wheel_view.setViewAdapter(monthAdapter);
        int monthInt = Integer.parseInt(month);
        second_wheel_view.setCurrentItem(monthInt - 1 < 0 ? 0 : monthInt - 1);

        updateDay(day);
        canGetDayVisibleItem = true;  //放在这里可以确保一开始显示的是当天日期

        if (isShowHour) {
            ArrayWheelAdapter hourAdapter = new ArrayWheelAdapter<String>(mContext, fourthContents);
            fourth_wheel_view.setViewAdapter(hourAdapter);
            fourth_wheel_view.setCurrentItem(0);
        }
        afterItemChanged(false);
    }

    private boolean canGetDayVisibleItem = false;

    @SuppressWarnings("rawtypes")
    protected void updateDay(String day) {
        DMLog.d("day = " + day);
        int tempItem = second_wheel_view.getCurrentItem();
        thirdContents = DateUtil.getInstance().getDayList(
                firstContents.get(first_wheel_view.getCurrentItem()), secondContents.get(tempItem));
        int tempCurrentItem = Integer.parseInt(day) - 1;
        if (canGetDayVisibleItem) {
            //用上一次 日（A） 的位置，和当前最新每月天数（B）比较，如果A >= B,
            //则需将thirdWheelView的currentItem设置为 B.size() - 1，即最后一天
            tempCurrentItem = third_wheel_view.getCurrentItem();
            tempCurrentItem = tempCurrentItem >= thirdContents.size() ? thirdContents.size() - 1 : tempCurrentItem;
        }
        ArrayWheelAdapter dayAdapter = new ArrayWheelAdapter<String>(mContext, thirdContents);
        third_wheel_view.setViewAdapter(dayAdapter);
        third_wheel_view.setCurrentItem(tempCurrentItem);
    }

    /**
     * 根据所点击的位置，确定需要显示几个WheelView
     *
     * @param second
     * @param third
     * @param fourth
     */
    public void setWheelViewVisibility(boolean second, boolean third, boolean fourth) {
        if (second) //设置second_wheel_view
        {
            second_wheel_view.setVisibility(View.VISIBLE);
        } else {
            second_wheel_view.setVisibility(View.GONE);
        }
        if (third) //设置third_wheel_view
        {
            third_wheel_view.setVisibility(View.VISIBLE);
        } else {
            third_wheel_view.setVisibility(View.GONE);
        }
        if (fourth) //设置fourth_wheel_view
        {
            fourth_wheel_view.setVisibility(View.VISIBLE);
        } else {
            fourth_wheel_view.setVisibility(View.GONE);
        }
    }

    @Override
    public void onChanged(WheelView wheel, int oldValue, int newValue) {
        if(wheel.getId() == R.id.first_wheel_view){
            onFirstWheelViewChanged();
        }else if(wheel.getId() == R.id.second_wheel_view){
            onSecondWheelViewChanged();
        }else if(wheel.getId() == R.id.third_wheel_view){
            onThirdWheelViewChanged();
        }else if(wheel.getId() == R.id.fourth_wheel_view){
            onFourthWheelViewChanged();
        }

    }

    /**
     * Item内容改变，或者完成按钮点击后，调用该方法来回调OnDownClickListener
     */
    protected void afterItemChanged(boolean isClickOnComplete) {
        if (null != mOnSelectedItemChanged) {
            String second = secondContents.size() > second_wheel_view.getCurrentItem()
                    ? secondContents.get(second_wheel_view.getCurrentItem()) : "";

            String third = thirdContents.size() > third_wheel_view.getCurrentItem()
                    ? thirdContents.get(third_wheel_view.getCurrentItem()) : "";

            String fourth = fourthContents.size() > fourth_wheel_view.getCurrentItem()
                    ? fourthContents.get(fourth_wheel_view.getCurrentItem()) : "";

            mOnSelectedItemChanged.onItemChanged(
                    firstContents.get(first_wheel_view.getCurrentItem()), second, third, fourth, isClickOnComplete);
        }
    }

    private void onFirstWheelViewChanged() {
        switch (wheelViewType) {
            case TYPE_COMMON:
                afterItemChanged(false);
                break;
            case TYPE_AREA:
                updateCities();
                break;
            case TYPE_TIME:
                //防止数组越界
                int currentItem = thirdContents.size() <= third_wheel_view.getCurrentItem()
                        ? thirdContents.size() - 1 : third_wheel_view.getCurrentItem();
                updateDay(thirdContents.get(currentItem).replace(" ", "").replace("日", ""));
                afterItemChanged(false);
                break;
        }
    }

    private void onSecondWheelViewChanged() {
        switch (wheelViewType) {
            case TYPE_AREA:
                if (third_wheel_view.getVisibility() == VISIBLE) {
                    updateAreas();
                } else {
                    afterItemChanged(false);
                }
                break;
            case TYPE_TIME:
                //防止数组越界
                int currentItem = thirdContents.size() <= third_wheel_view.getCurrentItem()
                        ? thirdContents.size() - 1 : third_wheel_view.getCurrentItem();
                updateDay(thirdContents.get(currentItem).replace(" ", "").replace("日", ""));
                afterItemChanged(false);
                break;
        }
    }

    private void onThirdWheelViewChanged() {
        switch (wheelViewType) {
            case TYPE_AREA:
                afterItemChanged(false);
                break;
            case TYPE_TIME:
                afterItemChanged(false);
                break;
        }
    }

    private void onFourthWheelViewChanged() {
        switch (wheelViewType) {
            case TYPE_TIME:
                afterItemChanged(false);
                break;
        }
    }

    /***
     * WheelView发生了滚动，选中的内容有变化
     */
    public interface OnSelectedItemChanged {
        void onItemChanged(String firstItem, String secondItem, String thirdItem, String fourthItem, boolean isClickOnComplete);
    }

    public interface OnClickListener {
        void onCancelClick();

        void onDownClick(String firstItem, String secondItem, String thirdItem, String fourthItem);
    }
}
